package com.zzedu.integration.yzs.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.zzedu.integration.oss.IOssClientService;
import com.zzedu.integration.oss.dto.FileInfoDTO;
import com.zzedu.integration.yzs.IYzsService;
import com.zzedu.integration.yzs.config.YzsConfig;
import com.zzedu.integration.yzs.vo.YzsEvaluationResult;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class YzsServiceImpl implements IYzsService {
    private static final Logger log = LoggerFactory.getLogger(YzsServiceImpl.class);
    @Autowired
    IOssClientService ossClientService;

    @Autowired
    YzsConfig yzsConfig;

    public YzsEvaluationResult automaticScoring(FileInfoDTO fileInfoDTO, String text, String uid,Long callTimeout,Long connectTimeout,Long readTimeout) {
        // 下载文件
        byte[] data = ossClientService.download(fileInfoDTO.getUrl());
        if (data == null) {
            return null;
        }
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("mode", "A")
                .addFormDataPart("text", text)
                .addFormDataPart("voice", fileInfoDTO.getOriginalFilename(),
                        RequestBody.create(data, MediaType.get("audio/mpeg")))
                .build();

        Request request = new Request.Builder()
                .addHeader("appkey", yzsConfig.getAppKey())
                .addHeader("session-id", uid )
                .post(requestBody)
                .url(yzsConfig.getUrl())
                .build();
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .callTimeout(callTimeout, TimeUnit.SECONDS)
                .connectTimeout(callTimeout, TimeUnit.SECONDS)
                .readTimeout(readTimeout, TimeUnit.SECONDS)
                .build();

        try (Response response = okHttpClient.newCall(request).execute();) {
            if (response.isSuccessful()) {
                String res = response.body().string();
                return JSON.parseObject(res, new TypeReference<YzsEvaluationResult>() {
                });
            }
        } catch (Exception e) {
            log.error("自动评分失败,详细:{}", e.getMessage());
        }
        return null;
    }

}
